/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package neuralmusic.simplemidiplayer;

import java.util.Vector;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiDevice.Info;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Transmitter;

/**
 * 
 * @author pjl
 */
public class MyMidiSystem {

	public Transmitter trans;
	// Receiver recv;
	public Receiver thru;

	public void openMidi() throws MidiUnavailableException {

		MidiDevice idev = null;// = MyMidiSystem.getMidiDevice(infos[3]);
		MidiDevice odev = null;// = MyMidiSystem.getMidiDevice(infos[5]);
		String inName[] = { "M1010LT", "Virtual" };
		// String outName[] = {"M1010LT", "Gervill"};
		String outName[] = { "Gervill" ,"Java Sound Synthesizer"};
		//
		for (String s : inName) {
			MidiDevice dev = findMidiIn(s);
			if (dev != null) {
				System.out.println(" Input" + s);
				idev = dev;
				break;
			}
		}

		for (String s : outName) {
			MidiDevice dev = findMidiOut(s);
			if (dev != null) {
				System.out.println(" Ouput" + s);

				odev = dev;
				break;
			}
		}

		idev.open();
		odev.open();

		trans = idev.getTransmitter();
		thru = odev.getReceiver();

	}

	MidiDevice findMidiIn(String devName) {
		MidiDevice dev;

		Info[] infos = MidiSystem.getMidiDeviceInfo();
		// Vector<MidiDevice.Info> list = new Vector<MidiDevice.Info>();
		for (Info info : infos) {

			System.out.println(info);

			try {
				dev = MidiSystem.getMidiDevice(info);
				if (dev.getMaxTransmitters() != 0) {
					if (dev.getDeviceInfo().toString().startsWith(devName)) {
						return dev;
					}

				}
			} catch (MidiUnavailableException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// cnt++;
		}

		return null;
	}

	static MidiDevice findMidiOut(String devName) {
		MidiDevice dev;

		Info[] infos = MidiSystem.getMidiDeviceInfo();
		Vector<MidiDevice.Info> list = new Vector<MidiDevice.Info>();
		for (Info info : infos) {
			try {
				dev = MidiSystem.getMidiDevice(info);
				System.out.println(info);
				if (dev.getMaxReceivers() != 0) {
					if (dev.getDeviceInfo().toString().startsWith(devName)) {
						return dev;
					}

				}
			} catch (MidiUnavailableException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// cnt++;
		}

		return null;
	}
}
